<template>
  <div>
    <div class="page-content pt-24">
      <div class="layout">
        <div class="left mr-24">
          <banner
            v-if="bannerList && bannerList.length > 0"
            :list="bannerList"
            class="mb-16"
          />

          <friendly-scroll-list
            :is-show-loading="showLoading"
            :is-empty="!listData || !listData.length"
            :is-error="currentState.error"
            :is-no-more="currentState.noMore"
            :is-requesting="currentState.requesting"
            :more-load-action="getList"
            :scroll-load-action="loadMore"
            @refresh="getList(true)"
          >
            <news-item
              v-for="(item, index) in listData"
              :key="index"
              :obj="item"
            />
          </friendly-scroll-list>
        </div>

        <div class="right">
          <topic-and-news
            :topic-list="hotTopicList"
            :news-list="latestNewsList"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import TopicAndNews from '@/components/TopicAndNews.vue';
import FriendlyScrollList from '@/components/FriendlyScrollList.vue';
import NewsItem from '@/components/NewsItem.vue';
import Banner from '@/components/Banner.vue';

const RELEASE_TIME_FIELD = 'release_timestamp';
const COUNT = 30;

export default {
  name: 'ChannelPage',

  components: {
    TopicAndNews,
    FriendlyScrollList,
    NewsItem,
    Banner
  },

  async asyncData({ params, $API }) {
    const { id } = params;

    // 要闻
    const isHeadline = `${id}` === '83';

    const getNewsList = async (id) => {
      // 要闻，请求专题的数据
      if (isHeadline) {
        const res = await $API.subjectListContents({
          topicId: process.env.HEADLINE_SUBJECT_ID,
          pageNum: 1,
          pageSize: COUNT
        })
        return res.list
      } else {
        const list = await $API.articleGetChannelList({
          channelId: id
        })
        return list
      }
    }

    const [list, topicRes, latestNewsListRes, bannerListRes] = await Promise.all([
      getNewsList(id),
      $API.subjectListHots(),
      $API.articleGetLastestNews(),
      $API.articleGetBannerList({ sourceType: 16 })
    ]);

    const currentState = {
      id,
      isHeadline,
      error: false,
      noMore: false,
      requesting: false,
      pageNum: 2
    };

    if (list.length === 0) {
      currentState.isEmpty = true;
    } else if (list && list.length < COUNT) {
      currentState.noMore = true;
    }

    return {
      listData: list,
      currentState,
      showLoading: false,
      hotTopicList: topicRes,
      latestNewsList: latestNewsListRes,
      bannerList: bannerListRes
    };
  },

  data() {
    return {
      bannerList: [],
      listData: [],
      hotTopicList: [], // 热门专题
      latestNewsList: [], // 最新资讯
      showLoading: true,
      currentState: {
        isHeadline: false,
        id: null,
        requesting: false,
        isEmpty: false,
        error: false,
        noMore: false,
        pageNum: 1
      }
    };
  },

  computed: {
    language() {
      return this.$store.state.app.language;
    },
    currentLastReleaseTime() {
      return this.getLastReleaseTime(this.listData);
    }
  },

  methods: {
    getLastReleaseTime(lst) {
      if (!Array.isArray(lst)) return null;
      const last = lst[lst.length - 1];
      return this.$pick(RELEASE_TIME_FIELD)(last) || null;
    },

    async getList(isClear = false) {
      const { isHeadline } = this.currentState
      if (isHeadline) {
        await this.getTopicNewsList(isClear)
      } else {
        await this.getChannelNewsList(isClear)
      }
    },

    // 获取专题新闻
    async getTopicNewsList(isClear = false) {
      if (this.currentState.requesting || this.currentState.isEmpty || this.currentState.noMore) return;

      if (isClear) {
        this.currentState.pageNum = 1;
        this.showLoading = true;
      }

      const { currentState, listData } = this;
      this.currentState = {
        ...currentState,
        requesting: true,
        error: false,
        noMore: false,
        isEmpty: false
      };

      try {
        const { list } = await this.$API.subjectListContents(
          {
            topicId: process.env.HEADLINE_SUBJECT_ID,
            pageNum: this.currentState.pageNum,
            pageSize: COUNT
          },
          { showErrorMsg: false }
        );

        const allList = isClear === true ? list : [...listData, ...list];
        const isEmpty = allList.length === 0;
        const noMore = (list && list.length) < COUNT;
        this.listData = allList;
        this.currentState = {
          ...this.currentState,
          isEmpty,
          noMore
        };
        this.currentState.pageNum++;
      } catch (e) {
        this.currentState.error = true;
      } finally {
        this.showLoading = false;
        this.currentState.requesting = false;
      }
    },

    // 获取频道新闻
    async getChannelNewsList(isClear = false) {
      if (this.currentState.requesting) return;

      if (isClear) {
        this.showLoading = true;
      }

      const { currentState, currentLastReleaseTime, listData } = this;
      this.currentState = {
        ...currentState,
        requesting: true,
        error: false,
        noMore: false,
        isEmpty: false
      };

      try {
        const list = await this.$API.articleGetChannelList(
          {
            channelId: currentState.id,
            lastReleaseTime: currentLastReleaseTime
          },
          { showErrorMsg: false }
        );

        const allList = isClear === true ? list : [...listData, ...list];
        const isEmpty = allList.length === 0;
        const noMore = (list && list.length) < COUNT;
        this.listData = allList;
        this.currentState = {
          ...this.currentState,
          isEmpty,
          noMore
        };
      } catch (e) {
        this.currentState.error = true;
      } finally {
        this.showLoading = false;
        this.currentState.requesting = false;
      }
    },

    loadMore() {
      if (this.currentState.noMore) return;
      this.getList();
    }
  }
};
</script>

<style lang="scss" scoped>
@import '~assets/styles/variable.scss';

.page-content {
  width: $page-width;
  margin: 0 auto;

  .layout {
    display: flex;

    .left {
      width: $page-left-width;
    }

    .right {
      width: $page-right-width;
    }
  }
}
</style>
